<template>
	<view class="upload">
		<view
			v-for="(item, index) in img_list"
			:key="index"
			class="upload_list"
			:style="{ marginBottom: isMargin ? '16rpx' : '' }"
		>
			<image class="upload_img" :src="item" mode=""></image>
			<image
				@click="close(index)"
				class="close"
				src="http://112.124.50.179:8888/imgs/chaoshan/close_.png"
				mode=""
			></image>
		</view>
		<view
			class="add"
			:style="{ backgroundColor: backgroundColor, marginBottom: isMargin ? '16rpx' : '' }"
			v-if="img_list.length < upLength"
			@click="uploadAImg"
		>
			<up-icon name="plus" size="40" :color="addColor"></up-icon>
		</view>
	</view>
</template>

<script setup>
import { getCurrentInstance, ref, reactive, watchEffect } from 'vue';
let props = defineProps({
	// 最大上传数量
	upLength: {
		type: Number
	},
	// 超过3张传递true
	isMargin: {
		type: Boolean
	},
	// 上传背景色
	backgroundColor: {
		type: String
	},
	// 加号颜色
	addColor: {
		type: String
	},
	formData: {},
	list: {}
});
const $chooseImg = getCurrentInstance().appContext.config.globalProperties.$chooseImg;
let emit = defineEmits(['sendImgList']);
const img_list = ref(props.list);
console.log('props.list', props.list);

watchEffect(() => {
	img_list.value = props.list || [];
	console.log('img_list.value', img_list.value);
});

const close = (index) => {
	img_list.value.splice(index, 1);
	emit('sendImgList', img_list.value);
};
const uploadAImg = () => {
	$chooseImg
		.chooseImg({
			formData: props.formData,
			countLimit: props.upLength - img_list.value.length
		})
		.then((res) => {
			// console.log(res)
			let status = res.map((ele) => {
				if (ele.img_url.statusCode != 200) {
					return false;
				} else {
					return true;
				}
			});
			// console.log(status)
			if (!status[0]) {
				uni.showToast({
					icon: 'none',
					title: '上传失败'
				});
				return;
			}
			setTimeout(() => {
				uni.showLoading();

				res.forEach((ele) => {
					img_list.value.push(JSON.parse(ele.img_url.data).fileUrl);
				});
				emit('sendImgList', img_list.value);
				uni.hideLoading();
			}, 500);
		});
};
defineExpose({
	img_list
});
</script>

<style lang="scss">
.upload {
	display: flex;
	flex-wrap: wrap;

	margin-right: -10rpx;

	.add {
		width: calc(33.33333% - 10rpx);
		margin-right: 10rpx;
		height: 216rpx;
		// margin-bottom: 16rpx;
		border-radius: 2rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.upload_list {
		width: calc(33.33333% - 10rpx);
		margin-right: 10rpx;
		height: 216rpx;
		position: relative;

		.upload_img {
			width: 100%;
			height: 100%;
			border-radius: 12rpx;
		}

		.close {
			position: absolute;
			width: 40rpx;
			height: 40rpx;
			right: 0;
			top: 0;
		}
	}
}
</style>
